var app;


$(function () {


    $(document).on('click','.show_more',function(){
        $(this).hide().parents('.list_tool').eq(0).prev().removeClass("hidden_text");
    }).on('click','.show_other',function(){
        $(this).hide().parents('.list_tool').prev().show().prev(".to_hide").hide();
    });

    toastr.options = {
        closeButton: false,
        debug: false,
        newestOnTop: true,//新消息是否排在最上层
        progressBar: false,//是否显示进度条
        positionClass: "toast-top-center",
        onclick: null,
        showDuration: "300",
        hideDuration: "1000",
        timeOut: "1500",
        extendedTimeOut: "1000",
        showEasing: "swing",
        hideEasing: "linear",
        showMethod: "fadeIn",
        hideMethod: "fadeOut"
    };

    $("#search_text").val("")
    app = new Vue({
        el: '#app',
        data: {
            lists: []
        }
    });


    $("#search_button").on('click', function () {
        searchData(1);
    })

    init();

});

function init() {
    save();
    searchData(1);
}

function del(ev) {
    var id = $(ev).attr("data-id")
    var fileId = $(ev).attr("data-fileid")
    var pageLimit = $('#pageLimit');
    var current = pageLimit.bootstrapPaginator("getPages").current;
    $.ajax({
        url: 'del',
        type: 'POST',
        data: {'id': id, 'fileId': fileId},
        dataType: 'JSON',
        success: function (callback) {
            if (callback != null && callback.code == "success") {
                searchData(0);
                var total = pageLimit.bootstrapPaginator("getPages").total;
                pageLimit.bootstrapPaginator("show", current > total ? total : current);

            } else {
                showPopover(button, "删除失败,稍后重试.");
            }
        }
    })
}

function searchData(page) {
    var search_text = $("#search_text").val();
    $("#noDateMsg").hide()
    $.ajax({
        url: 'search',
        type: 'POST',
        data: {'search_text': search_text, 'page': page, 'count': 10},
        dataType: 'JSON',
        success: function (callback) {
            if (callback != null && callback.code == "success") {
                $("#message").text("相关结果约: " + callback.numFound + " 个");
                if (callback.numFound == 0) {
                    toastr.warning("无搜索结果!");
                    $("#noDateMsg").show();
                    $("#example").hide();
                }else {
                    $("#example").show();
                    $(".toShow,.show_more,.show_other").show();
                    $(".toHide").hide();
                }
                app.lists = callback.data;

                if (page <= 1)
                    createPaginator(callback.totalPages < 1 ? 1 : callback.totalPages)
            } else {
                toastr.error("服务请求失败请稍后重试.");
            }
        }
    })
}

function createPaginator(totalPages) {
    $('#pageLimit').bootstrapPaginator({
        currentPage: 1,
        totalPages: totalPages,
        size: "normal",
        bootstrapMajorVersion: 3,
        alignment: "lift",
        numberOfPages: 10,
        itemTexts: function (type, page, current) {
            switch (type) {
                case "first":
                    return "首页";
                case "prev":
                    return "上一页";
                case "next":
                    return "下一页";
                case "last":
                    return "末页";
                case "page":
                    return page;
            }//默认显示的是第一页。
        },
        onPageClicked: function (event, originalEvent, type, page) {
            searchData(page)
        }
    });
}

/* 提示窗 */
function showPopover(target, msg) {
    target.attr("data-original-title", msg);
    $('[data-toggle="tooltip"]').tooltip();
    target.tooltip('show');
    target.focus();
    //2秒后消失提示框
    var id = setTimeout(function () {
            target.attr("data-original-title", "");
            target.tooltip('hide');
        },
        2000);
}


/* 提交时间 */
function save() {
    var modl_hs = true;
    $("#addDocSubmit").on('click', function () {
        if ($("#title").val() == "") {
            showPopover($("#title"), "请填写文档名称.");
            return false;
        } else if ($("#content").val() == "") {
            showPopover($("#content"), "请填写内容.");
            return false;
        }


        var formData = new FormData($("#addDoc")[0]);
        var button = $(this);
        $.ajax({
            //接口地址
            url: 'addDoc',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            beforeSend: function () {
                button.attr("disabled", "disabled").text("In submission..");
                modl_hs = false;
            },
            success: function (data) {
                //成功的回调 if(data.code == 300){ }
                button.removeAttr("disabled").text("Save");
                modl_hs = true;
                if (data != null && data.code == "success") {
                    $('#addDoc')[0].reset();
                    $("#input-file").fileinput('refresh')
                    toastr.success("提交成功.")
                    showPopover(button, "提交成功.");
                } else {
                    // showPopover(button, "提交失败,稍后重试.");
                    toastr.error("提交失败,稍后重试.");
                }
            },
            error: function (returndata) {
                showPopover(button, "网络访问失败，请稍后重试!");
                toastr.error("网络访问失败，请稍后重试!");
            }
        });
    })


    $('#exampleModal').on('hide.bs.modal', function (e) {
        return modl_hs;
    })
}


function initFileInput(ctrlName) {
    $("#input-file").fileinput({
        language: 'zh', //设置语言
        uploadUrl: "upload/UpLoadImage", //上传的地址
        // allowedFileExtensions: ['jpg', 'gif', 'png'],//接收的文件后缀
        //uploadExtraData:{"id": 1, "fileName":'123.mp3'},
        uploadAsync: true, //默认异步上传
        showUpload: false, //是否显示上传按钮
        showRemove: true, //显示移除按钮
        showPreview: false, //是否显示预览
        showCaption: false,//是否显示标题
        browseClass: "btn btn-primary", //按钮样式
        maxFileCount: 1, //允许同时上传的最大文件个数
        enctype: 'multipart/form-data',
        validateInitialCount: true,
        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",

    }).on('filepreupload', function (event, data, previewId, index) {     //上传中
        console.log('文件正在上传');
    }).on("fileuploaded", function (event, data, previewId, index) {    //一个文件上传成功
        var form = data.form, files = data.files, extra = data.extra,
            response = data.response, reader = data.reader;
        console.log(response);//打印出返回的json
        console.log(response.status);//打印出路径
    }).on('fileerror', function (event, data, msg) {  //一个文件上传失败
        console.log('文件上传失败！' + data.status);
    })
}
